//
//  HID3TagEditWC.m
//  HMusicPlayer
//
//  Created by hament deng on 14/10/24.
//  Copyright (c) 2014年 HJ. All rights reserved.
//

#import "HID3TagEditWC.h"
#import "TagReader.h"
#import "HCoreConfig.h"
#import "HSQLManager.h"
#import "HSongItem.h"
#import "HJAudioPlayer.h"


@interface HID3TagEditWC ()

@property (nonatomic,strong) NSImage * tempArtworkImg;//记录artwork,有些格式taglib解析不到

@end

@implementation HID3TagEditWC

- (void)windowDidLoad {
    [super windowDidLoad];
    
    // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
    
    
    
    
    //翻译
    self.albumImgLab.stringValue=NSLocalizedString(@"Album image:", nil);
    self.imgDesLab.stringValue=NSLocalizedString(@"Id3ImageDes", nil);
    self.titleLab.stringValue=NSLocalizedString(@"Title:", nil);
    self.albumLab.stringValue=NSLocalizedString(@"Album:", nil);
    self.genreLab.stringValue=NSLocalizedString(@"Genre:", nil);
    self.yearLab.stringValue=NSLocalizedString(@"Year:", nil);
    self.trackLab.stringValue=NSLocalizedString(@"Track:", nil);
    self.commentLab.stringValue=NSLocalizedString(@"Comment:", nil);
    self.artistLab.stringValue=NSLocalizedString(@"Artist:", nil);
    
    [self.saveBtn setTitle:NSLocalizedString(@"Save", nil)];
    
    self.window.title=NSLocalizedString(@"ID3 Tag Editor", nil);
    
}



-(void)configTagReader:(TagReader*)tagReader{


    self.currentReader=tagReader;
    NSData * albumData=self.currentReader.albumArt;
    if (albumData) {
        NSImage * img=[[NSImage alloc] initWithData:albumData];
        self.tempArtworkImg=img;//临时记录
        self.albumImgView.image=img;
    } else {
    
        //如果是m4a,aac,另外判断
        NSString * ext=self.currentEditsongItem.localPath.pathExtension.lowercaseString;
        if ([ext isEqualToString:@"aac"] || [ext isEqualToString:@"m4a"] || [ext isEqualToString:@"m4"]) {
    
            [HCoreConfig getSoundPropertyWithPath:self.currentEditsongItem.localPath completion:^(NSDictionary * dic){
                NSImage * aimg=dic[HArtwork];
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    if (aimg) {
                        self.tempArtworkImg=aimg;//临时记录
                        self.albumImgView.image=aimg;
                    }
                });
                
            }];
            
            
        }
    }


}

- (IBAction)imgChange:(NSImageView *)sender {
    
    @autoreleasepool {
        

        
    NSImage * image=[HCoreConfig imageResize:sender.image newSize:NSMakeSize(100, 100)];
    if (image) {
        sender.image=image;
        NSData *customimageData =[HCoreConfig imageConvertData:image imageFileType:NSJPEGFileType fitDeviceScale:NO];
        self.currentReader.albumArt =customimageData;
        self.tempArtworkImg=image;
    }
        }
    
}

- (IBAction)cleanImg:(NSButton *)sender {
    
     self.albumImgView.image=[NSImage imageNamed:NSImageNameAddTemplate];
    self.currentReader.albumArt =nil;
    self.tempArtworkImg=nil;
}


#pragma mark window delegate
-(void)windowWillClose:(NSNotification *)notification {
    
    [NSApp stopModal];
    if ([[HCoreConfig shareConfig].holdWindoControllerArr containsObject:self]) {
        
        //如果不是当前播放的曲目,关闭
        HSongItem * si=[HJAudioPlayer sharePlayer].currentPlaySongItem;
        if (si) {
            if (![si.localPath isEqualToString:self.currentEditsongItem.localPath]) {
                [HCoreConfig stopFilesAccessingSecurityScopedWithSongItem:self.currentEditsongItem];
            }
        }
        
        [[HCoreConfig shareConfig].holdWindoControllerArr removeObject:self];
    }
    
}

- (IBAction)save:(NSButton *)sender {
    
    
    //当前播放的文件不能被修改
    HSongItem * cusongItem=[HJAudioPlayer sharePlayer].currentPlaySongItem;
    if (cusongItem) {
        
        if ([cusongItem.syncid isEqualToString:self.currentEditsongItem.syncid]) {
            
            [HCoreConfig alertWithTitle:NSLocalizedString(@"CurrentSongEditErrorDES", nil) window:self.window];
            return;
        }
        
    }
    
    
    if (self.currentReader) {
        [self.window endEditingFor:nil];

        
       BOOL success=[self.currentReader save];
        if (success) {
          
            //暂时没用到,所以没更改数据库,将来加入按专辑和歌手排序,需要更新数据库
            //如果专辑名称被修改
            
            //如果作者名字被修改
            
            //如果文件名字被修改
            
            NSCharacterSet *  whitespaceSet= [NSCharacterSet whitespaceAndNewlineCharacterSet];
            NSString * nTx=[self.currentReader.title stringByTrimmingCharactersInSet:whitespaceSet];
            nTx=CHECKSTR(nTx);
            //检查总量是否为空
            if (![nTx isEqualToString:@""] ) {
                //如果名字被修改过
                if(![nTx isEqualToString:self.currentEditsongItem.songName]){
                    if(self.id3TagHandel){
                        self.id3TagHandel(nTx);
                    }
                    
                    
                }
                
            }

            
            //如果是m4a,aac,另外判断
            NSString * ext=self.currentEditsongItem.localPath.pathExtension.lowercaseString;
            if ([ext isEqualToString:@"aac"] || [ext isEqualToString:@"m4a"] || [ext isEqualToString:@"m4"]) {
            //如果有图片
                if(self.tempArtworkImg){
                //这个会重复写入property,所以放在最后
                   // [HCoreConfig writeSongInnerArtWorkWithPath:self.currentEditsongItem.localPath image:self.tempArtworkImg];
                     NSData *customimageData =[HCoreConfig imageConvertData:self.tempArtworkImg imageFileType:NSJPEGFileType fitDeviceScale:NO];
                    [TagReader writeArtworkForAAcWithPath:self.currentEditsongItem.localPath imageData:customimageData];
                }
             }
            
        }

    }
    [self.window close];
    
}





@end
